<?php
declare(strict_types=1);
/**
 * Created by PhpStorm.
 * User: zhangyawen
 * Date: 2021/7/14
 * Time: 11:40 PM
 */

namespace App\Exception\Handler;

use HKY\HyperfResponse\HttpServer\Contract\HKYResponseInterface;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\Logger\LoggerFactory;

use Hyperf\ExceptionHandler\ExceptionHandler;
use Psr\Container\ContainerInterface;
use Psr\Http\Message\ResponseInterface;
use App\Exception\BusinessException;
use Throwable;

class BusinessExceptionHandler extends ExceptionHandler
{
    const DEFAULT_BUSINESS_ERROR_CODE = -10001;

    /**
     * @var \Psr\Log\LoggerInterface
     */
    protected $logger;

    /**
     * @Inject()
     * @var RequestInterface
     */
    protected $request;

    /**
     * @Inject
     * @var HKYResponseInterface
     */
    protected $response;


    protected $container;

    public function __construct(LoggerFactory $loggerFactory, ContainerInterface $container)
    {
        $this->container = $container;
        $this->logger    = $loggerFactory->get('log');
    }

    public function handle(Throwable $throwable, ResponseInterface $response)
    {
        // 阻止异常冒泡
        $this->stopPropagation();

        // 请求信息
        $requestPath = $this->request->path();
        $requestData = json_encode($this->request->all(), JSON_UNESCAPED_UNICODE);

        $errCode = $throwable->getCode();
        $errMsg  = $throwable->getMessage();

        // 打日志
        $this->logger->error(sprintf('path:%s data:%s code:%s %s[%s] in %s Trace %s', $requestPath, $requestData, $errCode, $errMsg, $throwable->getLine(), $throwable->getFile(), $throwable->getTraceAsString()));

        if ($errCode <= 0) {// 错误码需要大于0
            $errCode = self::DEFAULT_BUSINESS_ERROR_CODE;
        }

        return $this->response->error($errMsg, $errCode);
    }

    /**
     * 判断该异常处理器是否要对该异常进行处理
     */
    public function isValid(Throwable $throwable): bool
    {
        return $throwable instanceof BusinessException;
    }
}